import axios from "axios";
import { Message } from "element-ui"
import store from "@/store"

/**
 * @file
 * @description axios二次封装的文件
 */
axios.defaults.baseURL = "/api"; //基地址
axios.defaults.timeout = process.env.VUE_APP_TIMEOUT; //超时时间

/**
 * 请求拦截器
 */
axios.interceptors.request.use(config => {
    config.headers.Authorization = store.getters.token;
    return config
}, error => Promise.reject(error))

/**
 * 响应拦截器
 */
axios.interceptors.response.use(response => {
    const { data } = response.data
    return data
}, error => {
    const msg = error.tostring();
    if (msg.includes('Timeout')) {
        Message.error('请求连接超时，请稍后再试');
        return Promise.reject(error);
    };
    if (msg.includes('Netword Error')) {
        Message.error('您的网络错误，请查看你都网络是否连接');
        return Promise.reject(error);
    };
    const { status } = response.error;
    switch (status) {
        case 401:
            Message.error('登录过期，请你重新登录');
            break;
        case 404:
            const { msg } = error.response.data;
            Message.error(msg || '请求接口不存在');
            break;
        case 500:
            Message.error('服务器内部错误');
            break;
    }
    return Promise.reject(error);
})

export default axios